/*
 * @Descripttion: 
 * @version: 
 * @Author: 
 * @Date: 2022-04-24 08:59:45
 * @LastEditors: weidelong
 * @LastEditTime: 2022-05-07 18:15:28
 */
import { createRouter, createWebHashHistory } from 'vue-router'
import index from '@/views/index.vue'
import store from "../store"

const routes = [
  {
    path: '/',
    name: 'index',
    redirect: '/home',
    component: index,
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home/home.vue')
      },
      {
        path: '/consult',
        name: 'consult',
        component: () => import('@/views/consult/consult.vue'),
        meta:{
          requireAuth: true
        }
      },
      {
        path: '/interactive',
        name: 'interactive',
        component: () => import('@/views/consult/interactive.vue'),
        meta:{
          requireAuth: true
        }
      },
      {
        path: '/detail',
        name: 'detail',
        component: () => import('@/views/home/details.vue'),
        meta:{
          requireAuth: true
        }
      },
      {
        path: '/social',
        name: 'social',
        component: () => import('@/views/social/social.vue'),
        meta:{
          requireAuth: true
        }
      },
      {
        path: '/release',
        name: 'release',
        component: () => import('@/views/social/release.vue'),
        meta:{
          requireAuth: true
        }
      },
      {
        path: '/mine',
        name: 'mine',
        component: () => import('@/views/mine/mine.vue')
      },
      {
        path: '/setup',
        name: 'setup',
        component: () => import('@/views/mine/setup.vue'),
        meta:{
          requireAuth: true
        }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login.vue'),
    meta:{
      cheakIsLogin: true
    }
  },
  {
    path: '/regist',
    name: 'regist',
    component: () => import('@/views/login/regist.vue'),
    meta:{
      cheakIsLogin: true
    }
  },

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  // 前往的路由是否需要验证
  if (to.meta.requireAuth) {
    // 是否有登录，有则跳过
    let isLogin = JSON.parse(sessionStorage.getItem('isLogin'))
    if (!isLogin) {
      //拦截路由, 用户未登录
      next('./login')
    } else {
      // next()
    }
  }
  //登陆、注册守卫
  if (to.meta.cheakIsLogin) {
    if(store.state.isLogin){
      //路由让其返回至原来的地址
      router.back()
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router